package com.xxdh.controller.work;


import com.xxdh.domain.dto.WorkDto;
import com.xxdh.domain.vo.WorkStudentVo;
import com.xxdh.domain.vo.WorkTeacherVo;
import com.xxdh.exception.BusiException;
import com.xxdh.service.IWorkService;
import com.xxdh.util.ConstansUtil;
import com.xxdh.util.Result;
import com.xxdh.util.UserHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

@RequestMapping("/work")
@RestController
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class WorkController {
    private final IWorkService workService;

    /**
     * 上传作业文件
     * @param file
     * @return
     */
    @PostMapping("/uploadWorkFile")
    public String uploadWorkFile(@RequestParam("file") MultipartFile file) {
        String filePath = "";
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 设置文件
            //保存路径（这里只是示例，实际中应该使用更安全的路径）
            String UPLOAD_DIR = ConstansUtil.FILEPATH+UUID.randomUUID().toString()+"\\";
            filePath = UPLOAD_DIR + fileName;
            // 创建文件保存路径
            File dest = new File(filePath);
            // 确保目录存在
            dest.getParentFile().mkdirs();
            // 将文件保存到指定路径
            file.transferTo(dest);
        } catch (Exception e) {
            throw new BusiException("作业文件失败");
        }
        return Result.ok(filePath).toJSONString();
    }

    @PostMapping("/addWork")
    public String addWork(@RequestBody WorkDto workDto){
        workService.addWork(workDto);
        return Result.ok().toJSONString();
    }

    /**
     * 学生查看未提交作业列表
     * @return
     */
    @GetMapping("/getWorkList-student")
    public String getWorkListByStudent(){
        Long userId = UserHolder.getUserId();
        List<WorkStudentVo> result = workService.getWorkListByStudent(userId);
        return Result.ok(result).toJSONString();
    }

    /**
     * 老师查看作业列表
     * @return
     */
    @GetMapping("/getWorkList-teacher")
    public String getWorkListByTeacher(){
        Long teacherId = UserHolder.getUserId();
        List<WorkTeacherVo> result = workService.getWorkListByTeacher(teacherId);
        return Result.ok(result).toJSONString();
    }


    /**
     * 查看作业文件
     * @param fileAddress 作业地址
     * @param response
     * @return
     */
    @GetMapping("/getWorkPdf")
    public String getWorkFile(@RequestParam String fileAddress, HttpServletResponse response) {
        // 构造PDF文件的完整路径
        Path filePath = Paths.get(fileAddress);

        // 设置HTTP响应头
        response.setContentType(MediaType.APPLICATION_PDF_VALUE);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + UUID.randomUUID().toString().substring(0,10) +".pdf"+ "\"");

        // 使用try-with-resources语句来确保InputStream和OutputStream在使用后被正确关闭
        try (InputStream inputStream = new FileInputStream(filePath.toFile());
             OutputStream outputStream = response.getOutputStream()) {

            // 使用缓冲区来传输数据，提高效率
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }catch (Exception e) {
            System.out.println("作业下载失败");
        }
        return Result.ok().toJSONString();
    }

    /**
     * 删除作业
     * @param workId 作业id
     * @return
     */
    @PostMapping("/deleteWork")
    public String deleteWork( @RequestParam String workId){
        workService.deleteWork(workId);
        return Result.ok().toJSONString();
    }

    /**
     * 提交作业
     * @param workId
     * @return
     */
    @PostMapping("/submitWork")
    public String submitWork( @RequestParam String workId,@RequestParam String fileAddress){
        Long studentId = UserHolder.getUserId();
        workService.submitWork(studentId,workId,fileAddress);
        return Result.ok().toJSONString();
    }

    /**
     * 查看学生提交的某个作业列表
     * @param workId 作业id
     * @return 返回学生名字和作业地址
     */
    @GetMapping("/getStudentWorkList")
    public String getStudentWork(@RequestParam String workId){
        List<WorkTeacherVo> result = workService.getWorkListByWorkId(workId);
        return Result.ok(result).toJSONString();
    }
}
